package basketball

import (
	"longmen/server/config/global"
	global2 "longmen/server/config/global"
	basketball_behaviour2 "longmen/server/internal/services/nami/api/v5/sports/basketball/basketball_behaviour"
	"longmen/server/internal/services/nami/config"
	"longmen/server/internal/services/nami/utils/restyclient"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"time"
)

var defineEventID = []int{1, 3} // 1 NBA, 3 CBA

func SyncCompPoint() {
	for i := 0; i < len(defineEventID); i++ {
		resp := basketball_behaviour2.CompPoint{}
		queryStr := config.BuildParamsAndUserAndSecret(map[string]interface{}{
			"id": defineEventID[i],
		})
		err := restyclient.GetUrlAndBindRecords(config.BBCompPoint+queryStr, &resp)
		if err != nil {
			global2.Log.Error("获取更新列表失败: ", err)
			return
		}

		if len(resp.Results.Tables) > 0 {
			for _, v := range resp.Results.Tables {
				for _, ch := range v.Rows {
					var tempTeam models_sports.BasketballTeam
					err := global.Sport().Model(&tempTeam).Where("id=?", ch.TeamID).First(&tempTeam).Error
					if err != nil {
						global2.Log.Error("球队信息不存在,更新数据失败: ", err)
						continue
					}
					r := &models_sports.BasketballPoint{
						ID:               ch.TeamID,
						TeamID:           ch.TeamID,
						TeamLogo:         tempTeam.Logo,
						TeamName:         tempTeam.NameZh,
						CompID:           defineEventID[i],
						Scope:            v.Scope,
						Name:             v.Name,
						StageID:          v.StageID,
						Position:         ch.Position,
						Note:             ch.Note,
						Won:              ch.Won,
						Lost:             ch.Lost,
						WonRate:          ch.WonRate,
						GameBack:         ch.GameBack,
						PointsAvg:        ch.PointsAvg,
						PointsAgainstAvg: ch.PointsAgainstAvg,
						DiffAvg:          ch.DiffAvg,
						Streaks:          ch.Streaks,
						Home:             ch.Home,
						Away:             ch.Away,
						Division:         ch.Division,
						Conference:       ch.Conference,
						Last_10:          ch.Last_10,
						Points:           ch.Points,
						PointsFor:        ch.PointsFor,
						PointsAgt:        ch.PointsAgt,
						SeasonID:         resp.Results.SeasonID,
						UpdatedAt:        time.Now(),
						TeamNameEn:       tempTeam.ShortNameEn,
					}
					rows := global2.Sport().Model(&models_sports.BasketballPoint{}).Where("id = ? and scope=?", r.ID, v.Scope).Updates(&r).RowsAffected
					if rows == 0 {
						err := global2.Sport().Model(&models_sports.BasketballPoint{}).Create(&r).Error
						if err != nil {
							global2.Log.Error("球队数据更新数据失败: ", err)
							continue
						}
					}
				}
			}
		}
	}

	// log.Printf("basketball: %+v", resp)
}
